import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:package_info_plus/package_info_plus.dart';
import 'location_utils.dart'; // 引入定位工具类
import 'package:flutter/widgets.dart'; 
import '../manger/user_manger.dart';
import '../manger/global_config.dart';
import '../manger/uniqueIdentifier_manager.dart';
import 'dart:io'; // 引入 dart:io 库
import '../l10n/app_localizations.dart';
class NetworkUtils {
  static const String baseUrl = UrlConfig.baseUrl; // 替换为你的实际基础 URL

  static Future<dynamic> get(
  RequestCmd cmd, {
  Map<String, String>? headers,
  Map<String, dynamic>? params,
  bool isLoading = false,
  ValueNotifier<bool>? loadingNotifier,
}) async {
  headers = await _addDefaultHeaders(headers);
  // print("Params: $params");

  final queryString = params != null && params.isNotEmpty ? '?${params.entries.map((e) => '${e.key}=${e.value}').join('&')}' : '';
  final uri = Uri.parse('$baseUrl/api${cmd.codeValue}$queryString');

  // print("get url: $uri");

  if (isLoading && loadingNotifier != null) loadingNotifier.value = true;

  try {
    final response = await http.get(uri, headers: headers);
    return _handleResponse(response);
  } catch (e) {
    rethrow;
  } finally {
    if (isLoading && loadingNotifier != null) loadingNotifier.value = false;
  }
}

static Future<dynamic> post(
  RequestCmd cmd, {
  Map<String, String>? headers,
  dynamic body,
  bool isLoading = false,
  ValueNotifier<bool>? loadingNotifier,
}) async {
  headers = await _addDefaultHeaders(headers);

  final url = Uri.parse('$baseUrl/api${cmd.codeValue}');
  // final url = Uri.parse('$baseUrl${cmd.codeValue}');
  // print(body);
  if (isLoading && loadingNotifier != null) loadingNotifier.value = true;

  try {
    final response = await http.post(
      url,
      headers: headers,
      body: json.encode(body),
    );
    return _handleResponse(response);
  } catch (e) {
    rethrow;
  } finally {
    if (isLoading && loadingNotifier != null) loadingNotifier.value = false;
  }
}


  static Future<dynamic> delete(RequestCmd cmd, String address,{Map<String, String>? headers}) async {
    headers = await _addDefaultHeaders(headers);
    final url = Uri.parse('$baseUrl/api${cmd.codeValue}/$address');  // 使用枚举获取路径
    final response = await http.delete(url, headers: headers);
    return _handleResponse(response);
  }

static Future<Map<String, String>> _addDefaultHeaders(Map<String, String>? headers) async {
  headers ??= {};
  if (globalLocationData != null) {
    String locationDataBase64 = base64Encode(utf8.encode(globalLocationData!.toJson()));
    headers['qwer'] = locationDataBase64;
  } else {
    headers['qwer'] = '';
  }
  final String platformType = Platform.isIOS ? 'iOS' : 'Android';

  headers['clientType'] = platformType;
  headers['browserType'] = platformType;
  headers['Content-Type'] = 'application/json;charset=UTF-8';
  headers['Authorization'] = UserInfos.shared.token.isNotEmpty ? "Bearer ${UserInfos.shared.token}" : "";
  headers['cid'] = '';
  headers['languageCode'] = getLanguageCode();
  headers['currency'] = UserInfos.shared.currencyListModel?.currencyId.toString() ?? '23';

  final packageInfo = await PackageInfo.fromPlatform();
  headers['iOSVersion'] = packageInfo.version;

  // 获取唯一 deviceNumber
  String deviceNumber = await UniqueIdentifierManager().getUniqueIdentifier();
  // print('deviceNumber == $deviceNumber');
  headers['deviceNumber'] = deviceNumber;
  headers['language'] = isTraditionalChinese() ? '1' : '0';

  return headers;
}


  static dynamic _handleResponse(http.Response response) {
    switch (response.statusCode) {
      case 200:
        final decodedBody = utf8.decode(response.bodyBytes);
        return json.decode(decodedBody);
      case 400:
        throw Exception('Bad Request: ${response.body}');
      case 401:
      case 403:
        throw Exception('Unauthorized: ${response.body}');
      case 500:
        throw Exception('Internal Server Error: ${response.body}');
      default:
        throw Exception('Unexpected status code: ${response.statusCode}');
    }
  }
}

/// 请求接口类
enum RequestCmd {
  homeInfo,
  homeInfoen,
  homeInit,
  homeIniten,
  classList,
  classListen,
  pageList,
  pageListen,
  searchDetail,
  searchListen,
  couponsList,
  couponsList2,
  memberSpuCoupons,
  myCoupon,
  myCouponV1,
  commentPage,
  orderPage,
  orderPageen,
  getUserInfos,
  getById,
  feedBack,
  nameEdit,
  register,
  login,
  sendPhoneCode,
  sendcodeC,
  changePwd,
  memberBalanceLog,
  sendEmailCode,
  authenticationEmail,
  authenticationPhone,
  changeBind,
  checkout,
  cashier,
  check,
  checkSpuConfig,
  create,
  detail,
  cancel,
  listGroup,
  listGroupen,
  authorizelogin,
  waitPayment,
  logOutPhone,
  logOutEmail,
  getVersion,
  del,
  delen,
  t,
  refreshs,
  msgList,
  oauthconfig,
  getUseePayData,
  quickPayment,
  delCard,
  unKnown,
  msgOrderList,
  iospay,
  messagesread,
  address,
  voucherCode,
  logInfo,
  action,
}

extension RequestCmdExtension on RequestCmd {
  String get codeValue {
    switch (this) {
      case RequestCmd.homeInfo:
        return "/service/home/info";
       case RequestCmd.homeInfoen:
        return "/language/home/info";
      case RequestCmd.homeInit:
        return "/service/home/init";
      case RequestCmd.homeIniten:
        return "/service/home/init";
      case RequestCmd.classList:
        return "/service/category/list";
      case RequestCmd.classListen:
        return "/language/category/list";
      case RequestCmd.pageList:
        return "/service/spu/pageList";
      case RequestCmd.pageListen:
        return "/language/spu/pageList";
      case RequestCmd.searchDetail:
        return "/service/spu/detail-show";
      case RequestCmd.searchListen:
        return "/language/spu/detail-show";
      case RequestCmd.couponsList:
        return "/member/memberSpuCoupons/list";
      case RequestCmd.couponsList2:
        return "/member/memberSpuCoupons/listToken";
      case RequestCmd.myCoupon:
        return "/service/spuCoupons/dataList";
      case RequestCmd.myCouponV1:
        return "/service/spuCoupons/dataListV1";
      case RequestCmd.commentPage:
        return "/service/memberOrderEvaluate";
      case RequestCmd.login:
        return "/auth/login";
      case RequestCmd.orderPage:
        return "/service/order/pageList";
      case RequestCmd.orderPageen:
        return "/language/order/pageList";
      case RequestCmd.getUserInfos:
        return "/language/member/info";
      case RequestCmd.feedBack:
        return "/service/feedback/add";
      case RequestCmd.getById:
        return "/member/memberDetail/getById";
      case RequestCmd.nameEdit:
        return "/service/member/edit";
      case RequestCmd.register:
        return "/auth/register";
      case RequestCmd.changePwd:
        return "/service/member/changePwd";
      case RequestCmd.sendPhoneCode:
        return "/auth/sendPhoneCode";
      case RequestCmd.sendcodeC:
        return "/auth/codeC";
      case RequestCmd.memberBalanceLog:
        return "/member/memberBalanceLog/page";
      case RequestCmd.sendEmailCode:
        return "/auth/sendEmailCode";
      case RequestCmd.authenticationEmail:
        return "/auth/authenticationEmail";
      case RequestCmd.authenticationPhone:
        return "/auth/authenticationPhone";
      case RequestCmd.changeBind:
        return "/auth/changeBind";
      case RequestCmd.checkout:
        return "/language/order/confirm-payment";
      case RequestCmd.cashier:
        return "/service/order/cashier";
      case RequestCmd.check:
        return "/service/home/account/check";
      case RequestCmd.checkSpuConfig:
        return "/service/spu/checkSpuConfig";
      case RequestCmd.create:
        return "/service/order/create";
      case RequestCmd.detail:
        return "/service/order/detail";
      case RequestCmd.cancel:
        return "/service/order/cancel";
      case RequestCmd.listGroup:
        return "/member/memberMain/listGroup";
      case RequestCmd.listGroupen:
        return "/language/memberMain/listGroup";
      case RequestCmd.waitPayment:
        return "/service/order/waitPayment";
      case RequestCmd.logOutPhone:
        return "/auth/log-out-phone";
      case RequestCmd.logOutEmail:
        return "/auth/log-out-email";
      case RequestCmd.getVersion:
        return "/service/version";
      case RequestCmd.del:
        return "/member/memberMain/del";
      case RequestCmd.delen:
        return "/language/memberMain/del";
      case RequestCmd.refreshs:
        return "/auth/refresh";
      case RequestCmd.msgList:
        return "/member/messages/msgList";
      case RequestCmd.msgOrderList:
        return "/member/messages";
      case RequestCmd.iospay:
        return "/service/ios-pay";
      case RequestCmd.messagesread:
        return "/member/messages/read";
      case RequestCmd.getUseePayData:
        return "/service/order/getUseePayData";
      case RequestCmd.quickPayment:
        return "/service/order/quickPayment";
      case RequestCmd.delCard:
        return "/service/member/airwallex/delCard";
      case RequestCmd.address:
        return "/member/billing-address";
      case RequestCmd.voucherCode:
        return "/member/memberSpuCoupons/voucherCode";
      case RequestCmd.memberSpuCoupons:
      return "/member/memberSpuCoupons/memberSpuCoupons";
      case RequestCmd.oauthconfig:
      return "/service/oauth-config";
      case RequestCmd.authorizelogin:
        return "/auth/authorize-login";
      case RequestCmd.logInfo:
        return "/member/log-info";
      case RequestCmd.action:
        return "/service/home/action";
      case RequestCmd.t:
        return "/member/t?v=2&tid=G-9NVEQR6L37&gtm=45je4c40v9197807664z89192084846za200zb9192084846&_p=1733466004266&gcd=13l3l3l3l1l1&npa=0&dma=0";
      case RequestCmd.unKnown:
        return "";
    }
  }
}
